package com.dullong.firedocmanager.Controller;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.dullong.firedocmanager.JODConverter.Converter;
import com.dullong.firedocmanager.service.base.BaseService;
import com.dullong.firedocmanager.util.ConnectionUtil;
import com.dullong.firedocmanager.util.OptionUtil;
import com.dullong.firedocmanager.util.json.Jacksons;
import com.dullong.firedocmanager.util.json.SendJsonUtil;

@Controller
@RequestMapping("/file/upload")
public class UploadController {

	Jacksons jacksons = Jacksons.me();
	@Autowired
	Converter converter;
	@Autowired
	BaseService baseService;

	@ResponseBody
	@RequestMapping(value = "/upload.json", method = RequestMethod.POST)
	public String upload(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "qqfile", required = true) MultipartFile file)
			throws IllegalStateException, IOException, SQLException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		if (null == file || file.isEmpty()) {
			return "{\"success\": false}";
		}
		Long Id = getMaxId();
		if (Id == null) {
			return "{\"success\": false}";
		}
		final long size = file.getSize();
		final String contentType = file.getContentType();
		final String filename = file.getOriginalFilename();
		final String extension = FilenameUtils.getExtension(filename)
				.toLowerCase();
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
		/** 构建图片保存的目录 **/
		final String logoPathDir = "files/" + dateformat.format(new Date());
		String save_path_base = OptionUtil.getOption("opload_filePath");
		File f = new File(save_path_base + File.separator + logoPathDir
				+ File.separator + Id + "." + extension);

		File flor = new File(save_path_base + File.separator + logoPathDir);
		if (!flor.exists())
			flor.mkdirs();
		file.transferTo(f);

		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();

		runner.update(
				conn,
				"insert into document(ID,TITLE,TYPE,LENGTH,UPLOADTIME,CATE,UPLOADUSER) values(?,?,?,?,?,?,?)",
				Id, filename, extension, size, new Date().getTime(), 0,
				baseService.getUser().getUserName());
		runner.update(conn, "insert into doc_dir values(?,?,?)", Id, extension,
				logoPathDir + File.separator + Id + "." + extension);
		DbUtils.closeQuietly(conn);

		return "{\"success\": true,\"docid\": \"" + Id + "\",\"type\":\""
				+ extension + "\",\"docname\": \"" + filename + "\"}";
	}

	@RequestMapping(value = "/uploads.json", method = RequestMethod.POST)
	public ModelAndView upload(@RequestParam MultipartFile[] files,
			HttpServletRequest request, HttpServletResponse response) {
		if (null == files) {
			return null;
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (final MultipartFile file : files) {
			Map<String, Object> ju = new HashMap<String, Object>();
			if (!file.isEmpty()) {
				final long size = file.getSize();
				final String contentType = file.getContentType();
				final String filename = file.getOriginalFilename();
				final String extension = FilenameUtils.getExtension(filename)
						.toLowerCase();
				ju.put("size", "文件长度: " + size / 1024.0 + "KB");
				ju.put("contentType", "文件类型: " + contentType);
				ju.put("type", "文件名称: " + extension);
				ju.put("name", "文件原名: " + filename);

				SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
				/** 构建图片保存的目录 **/
				final String logoPathDir = "files/"
						+ dateformat.format(new Date());

				Connection conn = ConnectionUtil.getConnection();
				QueryRunner runner = new QueryRunner();
				try {
					Long name = (Long) runner.query(conn,
							"select max(id) as id from document",
							new ScalarHandler(1));
					name = name == null ? 0 : name;
					name++;
					ju.put("ID", name);
					runner.update(
							conn,
							"insert into document(ID,TITLE,TYPE,LENGTH,UPLOADTIME,CATE,UPLOADUSER) values(?,?,?,?,?,?,?)",
							name, filename, extension, size, new Date()
									.getTime(), 0, baseService.getUser()
									.getUserName());
					String save_path_base = OptionUtil
							.getOption("opload_filePath");
					File f = new File(save_path_base + File.separator
							+ logoPathDir + File.separator + name + "."
							+ extension);

					File flor = new File(save_path_base + File.separator
							+ logoPathDir);
					if (!flor.exists())
						flor.mkdirs();

					try {
						file.transferTo(f);
						runner.update(conn,
								"insert into doc_dir values(?,?,?)", name,
								extension, logoPathDir + File.separator + name
										+ "." + extension);
						if (!"pdf".equals(extension)) {

							File out_file = new File(save_path_base
									+ File.separator + logoPathDir
									+ File.separator + name + ".pdf");
							converter.convert(f, out_file);
							runner.update(conn,
									"insert into doc_dir values(?,?,?)", name,
									"pdf", logoPathDir + File.separator + name
											+ ".pdf");

						}

					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} finally {
						DbUtils.closeQuietly(conn);
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} finally {
					DbUtils.closeQuietly(conn);
				}

				list.add(ju);
			}
		}
		jacksons.putProperty("response", list);

		SendJsonUtil.sendJson(jacksons.write2String(), response);

		return null;

	}

	static Long maxNum = 0l;

	private synchronized static Long getMaxId() {
		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();
		try {
			Long id = (Long) runner.query(conn,
					"select max(id) as id from document", new ScalarHandler(1));
			id = id == null ? 0 : id;
			if (maxNum == 0l) {
				maxNum = id;
			}
			maxNum++;
			return maxNum;
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return null;
	}
}

